<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leaflet 地图示例</title>
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
          integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
          crossorigin=""/>
    <!-- Leaflet JavaScript -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
            integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
            crossorigin=""></script>
    <!-- Leaflet.heat 插件 -->
    <script src="https://unpkg.com/leaflet.heat/dist/leaflet-heat.js"></script>
    <!-- 通过CDN引入地图服务 -->
    <script src="http://localhost:3000/src/inject.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            height: 100vh;
            overflow: hidden;
        }
        .container {
            display: flex;
            flex-direction: row;
            height: 100vh;
            padding: 20px;
            box-sizing: border-box;
            gap: 20px;
        }
        .left-section {
            flex: 2;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .right-section {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
            min-width: 400px;
            max-height: 100%;
        }
        .map-section {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        #map {
            flex: 1;
            width: 100%;
        }
        .status-panel {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #f8f9fa;
            flex-shrink: 0;
        }
        .panel-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            padding-bottom: 5px;
            border-bottom: 1px solid #ddd;
        }
        .status-panel.connected .panel-title {
            color: #4CAF50;
        }
        .status-panel.disconnected .panel-title {
            color: #2196F3;
        }
        .ws-status {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 10px;
        }
        .ws-status.connected {
            background-color: #4CAF50;
        }
        .ws-status.disconnected {
            background-color: #2196F3;
        }
        .log-section {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
            overflow: hidden;
        }
        .log-section h3 {
            margin: 0 0 10px 0;
            flex-shrink: 0;
        }
        .log-panel {
            flex: 1;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            font-family: monospace;
            background-color: #f5f5f5;
            scrollbar-width: thin;
            scrollbar-color: #888 #f5f5f5;
            min-height: 0;
        }
        .log-panel::-webkit-scrollbar {
            width: 8px;
        }
        .log-panel::-webkit-scrollbar-track {
            background: #f5f5f5;
        }
        .log-panel::-webkit-scrollbar-thumb {
            background-color: #888;
            border-radius: 4px;
        }
        .log-panel::-webkit-scrollbar-thumb:hover {
            background-color: #555;
        }
        .log-entry {
            margin: 5px 0;
            padding: 5px;
            border-bottom: 1px solid #ddd;
        }
        .log-entry .direction {
            font-weight: bold;
            margin-bottom: 5px;
            padding: 2px 5px;
            border-radius: 3px;
            display: inline-block;
            font-size: 12px;
        }
        .log-entry.client .direction {
            background-color: #bbdefb;
            color: #1565c0;
        }
        .log-entry.server .direction {
            background-color: #e1bee7;
            color: #6a1b9a;
        }
        .log-entry.client {
            background-color: #e3f2fd;
        }
        .log-entry.server {
            background-color: #f3e5f5;
        }
        .button-container {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            background-color: #2196F3;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #1976D2;
        }
        .json-view {
            white-space: pre-wrap;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left-section">
            <h1>Leaflet 地图示例</h1>
            <div class="map-section">
                <div id="map"></div>
                <div class="button-container">
                    <button id="drawStarBtn">绘制五角星</button>
                    <button id="zoomToStarBtn">缩放到五角星</button>
                    <button id="clearAllBtn">清除所有</button>
                </div>
            </div>
        </div>
        <div class="right-section">
            <div class="status-panel disconnected">
                <div class="panel-title">WebSocket连接状态</div>
                <span class="ws-status disconnected" id="wsStatus"></span>
                <span id="wsStatusText">WebSocket未连接</span>
            </div>
            <div class="log-section">
                <h3>通信日志</h3>
                <div class="log-panel" id="logPanel"></div>
            </div>
        </div>
    </div>

    <script>
        // 检查 MapService 是否可用
        if (typeof MapService === 'undefined') {
            alert('请先运行 inject.js 文件服务，否则无法运行地图功能！\n请确保已启动服务器并且可以访问 http://localhost:3000/inject.js');
            throw new Error('MapService not found');
        }

        // 创建地图服务实例
        const mapService = new MapService();
        
        // 获取状态显示元素
        const wsStatus = document.getElementById('wsStatus');
        const wsStatusText = document.getElementById('wsStatusText');
        const logPanel = document.getElementById('logPanel');

        // 添加日志函数
        function addLog(message, type) {
            const entry = document.createElement('div');
            entry.className = `log-entry ${type}`;
            
            // 添加方向标识
            const direction = document.createElement('div');
            direction.className = 'direction';
            direction.textContent = type === 'client' ? '客户端 → 服务端' : '服务端 → 客户端';
            entry.appendChild(direction);
            
            // 添加消息内容
            const content = document.createElement('div');
            content.className = 'json-view';
            
            // 统一处理 JSON 格式
            try {
                // 如果消息已经是对象，直接使用
                const jsonData = typeof message === 'object' ? message : JSON.parse(message);
                content.innerHTML = JSON.stringify(jsonData, null, 2);
            } catch (e) {
                // 如果不是 JSON 格式，直接显示文本
                content.textContent = message;
            }
            
            entry.appendChild(content);
            logPanel.appendChild(entry);
            logPanel.scrollTop = logPanel.scrollHeight;
        }

        // 创建WebSocket事件监听器
        mapService.ws.addEventListener('open', () => {
            wsStatus.className = 'ws-status connected';
            wsStatusText.textContent = 'WebSocket已连接';
            document.querySelector('.status-panel').className = 'status-panel connected';
            addLog({ type: 'system', message: 'WebSocket连接已建立' }, 'server');
        });

        mapService.ws.addEventListener('message', (event) => {
            try {
                const response = JSON.parse(event.data);
                addLog(response, 'server');
            } catch (error) {
                addLog({ type: 'error', message: `解析服务器响应失败: ${error.message}` }, 'server');
            }
        });

        mapService.ws.addEventListener('error', (error) => {
            wsStatus.className = 'ws-status disconnected';
            wsStatusText.textContent = 'WebSocket连接错误';
            document.querySelector('.status-panel').className = 'status-panel disconnected';
            addLog({ type: 'error', message: `WebSocket错误: ${error.message}` }, 'server');
        });

        mapService.ws.addEventListener('close', () => {
            wsStatus.className = 'ws-status disconnected';
            wsStatusText.textContent = 'WebSocket已断开';
            document.querySelector('.status-panel').className = 'status-panel disconnected';
            addLog({ type: 'system', message: 'WebSocket连接已关闭' }, 'server');
        });

        // 代理 sendCommand 方法以添加日志
        const originalSendCommand = mapService.sendCommand;
        mapService.sendCommand = function(command, params) {
            const logMessage = {
                type: 'command',
                command,
                params,
                timestamp: new Date().toISOString()
            };
            addLog(logMessage, 'client');
            return originalSendCommand.call(this, command, params);
        };

        // 代理 sendFeedback 方法以添加日志
        const originalSendFeedback = mapService.sendFeedback;
        mapService.sendFeedback = function(command, success, message) {
            const logMessage = {
                type: 'feedback',
                command,
                success,
                message,
                timestamp: new Date().toISOString()
            };
            addLog(logMessage, 'client');
            if (originalSendFeedback) {
                return originalSendFeedback.call(this, command, success, message);
            }
        };

        // 确保 MapService 的原型上有 sendFeedback 方法
        if (!MapService.prototype.sendFeedback) {
            MapService.prototype.sendFeedback = function(command, success, message) {
                if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                    console.error('WebSocket未连接，无法发送反馈');
                    return;
                }

                try {
                    const feedback = {
                        type: 'feedback',
                        command,
                        success,
                        message,
                        timestamp: new Date().toISOString()
                    };
                    this.ws.send(JSON.stringify(feedback));
                } catch (error) {
                    console.error('发送反馈失败:', error);
                }
            };
        }
        
        // 初始化改为通过WebSocket控制
        mapService.init();
        
        // 添加一个标记
  

        // 按钮事件处理
        document.getElementById('drawStarBtn').onclick = () => mapService.drawStar();
        document.getElementById('zoomToStarBtn').onclick = () => mapService.zoomToStar();
        document.getElementById('clearAllBtn').onclick = () => {
            mapService.clearMarkers();
            mapService.clearPolygons();
        };


    </script>
</body>
</html>
